package com.jiang.剑指Offer.二分查找.BM17;

/**
 * @author Jiang
 * @version 1.0
 * @date 2024/12/16 23:06
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @param target int整型
     * @return int整型
     */
    public int search (int[] nums, int target) {
        // write code here
        // right等于数组长度
        int left = 0, right = nums.length;
        // if (right == 0) return -1; // 如果下面是left <= right, 就必须加这行代码，且还要修改right = mid + 1
        while(left < right) {
            int mid = (left + right) / 2; // 等同于(right - left) / 2 + left
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid;
            } else {
                left = mid + 1;
            }

        }
        return -1;

        // right等于数组最后一个元素下标
        // int left = 0, right = nums.length - 1;
        // while(left <= right) {
        //     int mid = (left + right) / 2;
        //     if (nums[mid] == target) {
        //         return mid;
        //     } else if (nums[mid] > target) {
        //         right = mid - 1;
        //     } else {
        //         left = mid + 1;
        //     }

        // }
        // return -1;
    }
}
